﻿using Finance.Infrastructrue.Interface;
using Finance.API.Write.Application.Command.ReceivablesManagementCommand;
using Finance.Domain;
using Finance.ErrorCode;
using MediatR;
using Org.BouncyCastle.Cms;
using AutoMapper;
using Finance.Infrastructrue.Implement;
using System.Transactions;
using Azure;

namespace Finance.API.Write.Application.Hander.ReceivablesManagementHander
{
    public class AddReceivablesManagementHander : IRequestHandler<AddReceivablesManagementCommand,APIResult<int>>
    {
        DatabaseContext db;
        IBaseRepository<ReceivablesManagement> recRep;
        ILogger<AddReceivablesManagementHander> logger;
        IMapper mapper;

        public AddReceivablesManagementHander(DatabaseContext db, IBaseRepository<ReceivablesManagement> recRep, ILogger<AddReceivablesManagementHander> logger, IMapper mapper)
        {
            this.db = db;
            this.recRep = recRep;
            this.logger = logger;
            this.mapper = mapper;
        }

        public  async Task<APIResult<int>> Handle(AddReceivablesManagementCommand request, CancellationToken cancellationToken)
        {
            APIResult<int> result = new APIResult<int>();
            try
            {
               

                    var mls = db.SqlSugar.Queryable<ReceivablesManagement>().First(a => !a.IsDel && a.FlowingWaterNumber == request.FlowingWaterNumber);
                    if (mls != null)
                    {
                        result.Code = APIEnum.Ok;
                        result.Message = "该编号已存在";
                        return await Task.FromResult(result);
                    }

                    var receivablesManagement = mapper.Map<ReceivablesManagement>(request);
                    receivablesManagement.IsDel = false;
                    var m = await db.SqlSugar.Insertable(receivablesManagement).ExecuteCommandAsync();


                   




                    if (m > 0)
                    {
                        result.Code = APIEnum.Ok;
                        result.Message = "应收管理添加成功";
                        result.Data = m;
                    }
                    else
                    {
                        result.Code = APIEnum.Fail;
                        result.Message = "应收管理添加失败";
                        result.Data = m;
                    }

                

               
                
            }
            catch (Exception ex)
            {

                logger.LogError( "应收管理添加报错" + ex.Message);
                throw;
            }
            return await Task.FromResult(result);
        }
    }
}
